//
//  HMLookAndThinkViewController.m
//  HeartMark
//
//  Created by rimi on 2016/11/6.
//  Copyright © 2016年 黄华强. All rights reserved.
//

#import "HMLookAndThinkViewController.h"
#import <AVOSCloud/AVOSCloud.h>
#import "HMLATNoteModel.h"
#import "HMLATNoteCell.h"
#import "HMNoteDetailsController.h"
#import "MJRefresh.h"
#import "HMAlertView.h"

@interface HMLookAndThinkViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UIButton * leftBtn;
@property(nonatomic,strong) UIButton * rightBtn;
@property(nonatomic,strong) NSMutableArray *otherHotNoteArr;
@property(nonatomic,strong) NSMutableArray *otherNewNoteArr;
@property(nonatomic,assign) BOOL isLeft;
@property(nonatomic,strong) UITableView *myTableView;
@property(nonatomic,strong) NSDate *date;
@property(nonatomic,strong) NSMutableArray *likeNoteArr;

@end


@implementation HMLookAndThinkViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self loadData];
}

- (void)loadData {
    
    AVUser* currentUser = [AVUser currentUser];
    // 读取 AVRelation 对象
    AVRelation *relation = [currentUser relationForKey:@"collectionNote"];
    
    // 获取关系查询
    AVQuery *likeQuery = [relation query];
    
    [likeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            [HMAlertView bottomAlertView:@"网络异常"];
        } else {
            for (AVObject *note in objects) {
                [self.likeNoteArr addObject:note];
            }
        }
    }];
    
    
    AVQuery *query = [AVQuery queryWithClassName:@"note"];
    [query whereKey:@"isPublic" equalTo:@"YES"];
    AVQuery *twoQuery = [AVQuery queryWithClassName:@"note"];
    [twoQuery whereKey:@"collectNumber" lessThan:@10];
    
    AVQuery *threeQuery = [AVQuery queryWithClassName:@"note"];
    [threeQuery whereKey:@"isDelete" notEqualTo:@"YES"];
    
    AVQuery *newQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:query,twoQuery,threeQuery,nil]];
    
    [newQuery orderByDescending:@"createdAt"];
    [newQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            [HMAlertView bottomAlertView:@"网络异常"];
        } else {
            
            for (AVObject *obj in objects) {
                _date = obj[@"createdAt"];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"MM月dd日 HH:mm"];
                NSString * currentDate = [formatter stringFromDate:_date];
                
                
                NSDictionary *dict = @{@"noteName":obj[@"authorName"],@"noteMessage":obj[@"content"],@"noteTime":currentDate,@"object":obj};
                
                HMLATNoteModel *model = [[HMLATNoteModel alloc] initWithHotDict:dict];
                
                [self.otherNewNoteArr addObject:model];
                
            }
            [self.myTableView reloadData];
        }
    }];
    
    
    
    AVQuery *priorityQuery = [AVQuery queryWithClassName:@"note"];
    [priorityQuery whereKey:@"collectNumber" greaterThan:@1];
    
    
    
    AVQuery *hotQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:query,priorityQuery,threeQuery,nil]];
    
    [hotQuery orderByDescending:@"collectNumber"];
    [hotQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
        if (error) {
            [HMAlertView bottomAlertView:@"网络异常"];
        } else {
            for (AVObject *obj in results) {
                _date = obj[@"createdAt"];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"MM月dd日 HH:mm"];
                NSString * currentDate = [formatter stringFromDate:_date];
                
                NSDictionary *dict = @{@"noteName":obj[@"authorName"],@"noteMessage":obj[@"content"],@"noteTime":currentDate,@"object":obj};
                
                HMLATNoteModel *model = [[HMLATNoteModel alloc] initWithHotDict:dict];
                [self.otherHotNoteArr addObject:model];
                
            }
            
            [self.myTableView reloadData];
        }
        
    }];
    
}

- (void)setupUI {
    self.automaticallyAdjustsScrollViewInsets = NO;
    _isLeft = YES;
    [self.view addSubview:self.myTableView];
    
    [self.myTableView registerClass:[HMLATNoteCell class] forCellReuseIdentifier:@"noteCell"];
    //下拉刷新
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadNewData];
    }];
    //上拉刷新
    self.myTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupNavigationView];
}

- (void)loadNewData {
    if (_isLeft) {
        AVQuery *zeroQuery = [AVQuery queryWithClassName:@"note"];
        [zeroQuery whereKey:@"isPublic" equalTo:@"YES"];
        AVQuery *oneQuery = [AVQuery queryWithClassName:@"note"];
        [oneQuery whereKey:@"collectNumber" greaterThan:@1];
        
        
        AVQuery *threeQuery = [AVQuery queryWithClassName:@"note"];
        [threeQuery whereKey:@"isDelete" notEqualTo:@"YES"];

        
        AVQuery *hotQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:zeroQuery,oneQuery,threeQuery,nil]];
        
        
        [hotQuery orderByDescending:@"collectNumber"];
        [hotQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
            [self.myTableView.mj_header endRefreshing];

            if (error) {
                [HMAlertView bottomAlertView:@"网络异常"];
            } else {
                
            NSMutableArray *resultsArr = [[NSMutableArray alloc] init];
            for (AVObject *obj in results) {
                _date = obj[@"createdAt"];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"MM月dd日 HH:mm"];
                NSString * currentDate = [formatter stringFromDate:_date];
                
                NSDictionary *dict = @{@"noteName":obj[@"authorName"],@"noteMessage":obj[@"content"],@"noteTime":currentDate,@"object":obj};
                
                HMLATNoteModel *model = [[HMLATNoteModel alloc] initWithHotDict:dict];
                [resultsArr addObject:model];
                
            }
            self.otherHotNoteArr = resultsArr;
            [self.myTableView reloadData];
            
            }
            
        }];
        
    } else {
        
        AVQuery *zeroQuery = [AVQuery queryWithClassName:@"note"];
        [zeroQuery whereKey:@"isPublic" equalTo:@"YES"];
        AVQuery *oneQuery = [AVQuery queryWithClassName:@"note"];
        [oneQuery whereKey:@"collectNumber" lessThan:@10];
        
        AVQuery *threeQuery = [AVQuery queryWithClassName:@"note"];
        [threeQuery whereKey:@"isDelete" notEqualTo:@"YES"];
        
        AVQuery *newQuery;
        
        if ([self.otherNewNoteArr count] == 0) {
             newQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:zeroQuery,oneQuery,threeQuery,nil]];
        } else {
          
            AVQuery *twoQuery = [AVQuery queryWithClassName:@"note"];
            HMLATNoteModel *firstObjModel = self.otherNewNoteArr.firstObject;
            AVObject *firstObj = firstObjModel.object;
            
            NSDate *firstDate = firstObj[@"createdAt"];
            [twoQuery whereKey:@"createdAt" greaterThan:firstDate];//查询已有数据最新时间之前的
            
            
            
            newQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:zeroQuery,oneQuery,twoQuery,threeQuery,nil]];
        }
        
       
        
        [newQuery orderByAscending:@"updatedAt"];
        [newQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
            [self.myTableView.mj_header endRefreshing];
            if (error) {
                [HMAlertView bottomAlertView:@"网络异常"];
            } else {
            
            for (AVObject *obj in results) {
                _date = obj[@"createdAt"];
                
                NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                [formatter setDateFormat:@"MM月dd日 HH:mm"];
                NSString * currentDate = [formatter stringFromDate:_date];
                
                NSDictionary *dict = @{@"noteName":obj[@"authorName"],@"noteMessage":obj[@"content"],@"noteTime":currentDate,@"object":obj};
                
                HMLATNoteModel *model = [[HMLATNoteModel alloc] initWithHotDict:dict];
                if ([self.otherNewNoteArr count] == 0) {
                    [self.otherNewNoteArr addObject:model];
                } else {
                [self.otherNewNoteArr insertObject:model atIndex:0];
                }
            }
            
            [self.myTableView reloadData];
            
            }
            
        }];
        
    }
    
    
}

- (void)loadMoreData {
    if (_isLeft) {
        AVQuery *zeroQuery = [AVQuery queryWithClassName:@"note"];
        [zeroQuery whereKey:@"isPublic" equalTo:@"YES"];
        AVQuery *oneQuery = [AVQuery queryWithClassName:@"note"];
        [oneQuery whereKey:@"collectNumber" greaterThan:@1];
        
        AVQuery *threeQuery = [AVQuery queryWithClassName:@"note"];
        [threeQuery whereKey:@"isDelete" notEqualTo:@"YES"];

        
        AVQuery *hotQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:zeroQuery,oneQuery,threeQuery,nil]];
        
        
        [hotQuery orderByDescending:@"collectNumber"];
        [hotQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
            [self.myTableView.mj_footer endRefreshing];
            
            if (error) {
                [HMAlertView bottomAlertView:@"网络异常"];
            } else {
            
            NSMutableArray *resultArr = [[NSMutableArray alloc] init];
                for (AVObject *obj in results) {
                    _date = obj[@"createdAt"];
                    
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    [formatter setDateFormat:@"MM月dd日 HH:mm"];
                    NSString * currentDate = [formatter stringFromDate:_date];
                    
                    NSDictionary *dict = @{@"noteName":obj[@"authorName"],@"noteMessage":obj[@"content"],@"noteTime":currentDate,@"object":obj};
                    
                    HMLATNoteModel *model = [[HMLATNoteModel alloc] initWithHotDict:dict];
                    [resultArr addObject:model];
                    
                }
            self.otherHotNoteArr = resultArr;
                [self.myTableView reloadData];
                
            }
            
        }];
        
    } else {
        AVQuery *zeroQuery = [AVQuery queryWithClassName:@"note"];
        [zeroQuery whereKey:@"isPublic" equalTo:@"YES"];
        AVQuery *oneQuery = [AVQuery queryWithClassName:@"note"];
        [oneQuery whereKey:@"collectNumber" lessThan:@10];
        
        AVQuery *threeQuery = [AVQuery queryWithClassName:@"note"];
        [threeQuery whereKey:@"isDelete" notEqualTo:@"YES"];
        
        
        
        AVQuery *newQuery;
        if ([self.otherNewNoteArr count] == 0) {
            newQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:zeroQuery,oneQuery,threeQuery,nil]];
        } else {
            AVQuery *twoQuery = [AVQuery queryWithClassName:@"note"];
            HMLATNoteModel *lastObjModel = self.otherNewNoteArr.lastObject;
            AVObject *lastObj = lastObjModel.object;
            
            NSDate *lastDate = lastObj[@"createdAt"];
            [twoQuery whereKey:@"createdAt" lessThan:lastDate];//查询已有数据最新时间之前的
            newQuery = [AVQuery andQueryWithSubqueries:[NSArray arrayWithObjects:zeroQuery,oneQuery,twoQuery,threeQuery,nil]];
        }
        
        
        
        
        [newQuery orderByDescending:@"createdAt"];
        [newQuery findObjectsInBackgroundWithBlock:^(NSArray *results, NSError *error) {
            [self.myTableView.mj_footer endRefreshing];
            if (error) {
                [HMAlertView bottomAlertView:@"网络异常"];
            } else {
            
                for (AVObject *obj in results) {
                    _date = obj[@"createdAt"];
                    
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    [formatter setDateFormat:@"MM月dd日 HH:mm"];
                    NSString * currentDate = [formatter stringFromDate:_date];
                    
                    NSDictionary *dict = @{@"noteName":obj[@"authorName"],@"noteMessage":obj[@"content"],@"noteTime":currentDate,@"object":obj};
                    
                    HMLATNoteModel *model = [[HMLATNoteModel alloc] initWithHotDict:dict];
                    if ([self.otherNewNoteArr count] == 0) {
                        [self.otherNewNoteArr addObject:model];
                    } else {

                    [self.otherNewNoteArr addObject:model];
                    }
                }
                [self.myTableView reloadData];
                
            }
            
        }];

    }
    
    
}

-(void) setupNavigationView  {
    
    UIView * titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    
    _leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH / 2, 44)];
    [_leftBtn setTitle:@"热门" forState:(UIControlStateNormal)];
    [_leftBtn addTarget:self action:@selector(topBtnClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [_leftBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
    
    _rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 2 ,0, SCREEN_WIDTH / 2, 44)];
    [_rightBtn setTitle:@"最新" forState:(UIControlStateNormal)];
    [_rightBtn addTarget:self action:@selector(topBtnClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    [_rightBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    
    [titleView addSubview:_leftBtn];
    [titleView addSubview:_rightBtn];
    
    self.navigationItem.titleView = titleView;
}

-(void) topBtnClicked:(UIButton *)button {
    
    if (button == _rightBtn && _isLeft) {
        [_leftBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        [_rightBtn setTitleColor:[UIColor greenColor] forState:(UIControlStateNormal)];
        _isLeft = NO;
        
        [self.myTableView reloadData];
    } else if (button == _leftBtn && !_isLeft) {
        [_leftBtn setTitleColor:[UIColor redColor] forState:(UIControlStateNormal)];
        [_rightBtn setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
        _isLeft = YES;
        [self.myTableView reloadData];
    }
    
}


#pragma mark - tableView代理方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HMNoteDetailsController *noteDetailsVC = [[HMNoteDetailsController alloc] init];
    if (_isLeft) {
        noteDetailsVC.model = self.otherHotNoteArr[indexPath.row];
    } else {
        noteDetailsVC.model = self.otherNewNoteArr[indexPath.row];
        
    }
    
    for (AVObject *note in self.likeNoteArr) {
        if ([note isEqual:noteDetailsVC.model.object])  {
            noteDetailsVC.isLike = YES;
        }
    }
    noteDetailsVC.myBlock = ^(AVObject *obj,NSString *isAdd) {
        if ([isAdd isEqualToString:@"YES"]) {
            [self.likeNoteArr addObject:obj];
        } else {
            for (AVObject *note in self.likeNoteArr) {
                if ([note isEqual:obj]) {
                    [self.likeNoteArr removeObject:note];
                    break;
                }
            }
        }
    };
    
    [self.navigationController pushViewController:noteDetailsVC animated:YES];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_isLeft) {
        return self.otherHotNoteArr.count;
    } else {
        return self.otherNewNoteArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HMLATNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:@"noteCell" forIndexPath:indexPath];
    if (_isLeft) {
        cell.model = self.otherHotNoteArr[indexPath.row];
    } else {
        cell.model = self.otherNewNoteArr[indexPath.row];
    }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}

#pragma mark - 一些懒加载方法
- (UITableView *)myTableView {
    if (!_myTableView) {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 108)];
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
    }
    return _myTableView;
}

- (NSMutableArray *)otherHotNoteArr {
    if (!_otherHotNoteArr) {
        _otherHotNoteArr = [[NSMutableArray alloc] init];
    }
    return _otherHotNoteArr;
}

-(NSMutableArray *)otherNewNoteArr {
    if (!_otherNewNoteArr) {
        _otherNewNoteArr = [[NSMutableArray alloc] init];
    }
    return _otherNewNoteArr;
}

- (NSMutableArray *)likeNoteArr {
    if (!_likeNoteArr) {
        _likeNoteArr = [[NSMutableArray alloc] init];
    }
    return _likeNoteArr;
}

@end
